#include "textedit.h"
#include "ui_textedit.h"
#define SavePath ("SavePath")

TextEdit::TextEdit(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TextEdit)
{
    ui->setupUi(this);
}

TextEdit::~TextEdit()
{
    delete ui;
}


void TextEdit::saveText()
{
    //QFile textFile;//OR : QFile textFile("text.txt");
    QDir dir;
    QString dirpath= qApp->applicationDirPath()+"/textDir/";
    dir.mkpath(dirpath);
    //创建新目录,dirpath中的所有未创建的子文件夹都将被创建
    //    dir.setPath(dirCur);//设置当前路径
    //    dir.mkdir(dirName);
    QString file_path= qApp->applicationDirPath()+"/textDir/text.txt";
    textFile.setFileName(file_path);
    if(!textFile.open(QIODevice::WriteOnly  | QIODevice::Text /*| QIODevice::Append*/))
    {
        qDebug("open FILED!");
        return;
    }
//    QTextStream write(&textFile);
//    write.setCodec("UTF-8");
//    write<<"QTextStream\n";
    textFile.write("TEST TEXT:\n");   //写入文字
    QString text = ui->textEdit->toPlainText();
    textFile.write(text.toStdString().c_str());
    textFile.close();
    return;
}

void TextEdit::readText()
{
  QString file_path= qApp->applicationDirPath()+"/textDir/text.txt";
  QFile textFile(file_path);
   if (!textFile.open(QIODevice::ReadOnly))
   {
       qDebug("open FILED!");
       return;
   }
   QString text = textFile.readAll();
   QStringList textList = text.split("\n");
   textList.removeAt(0);
   text = textList.join("\n");
   text.prepend("Text:\n");
   ui->textEdit->setText(text);
   textFile.close();
}

void TextEdit::on_pushButton_clicked()
{
   saveText();
}

void TextEdit::on_pushButton_2_clicked()
{
   readText();
}

void TextEdit::on_pushButton_3_clicked()
{
    ui->textEdit->clear();
    if (textFile.exists())
        textFile.remove();
}

void TextEdit::on_pushButton_4_clicked()
{
    QString file_path2= qApp->applicationDirPath()+"/textDir/text.txt";
    QFile textFile2(file_path2);
    if (!textFile2.exists()) // 判断.ngc和.ISO是否存在,生成文件（有ngc文件优先另存ngc） -SGX
    {

        QMessageBox msg(QMessageBox::Warning, tr("找不到文件"),
                        tr("找不到文件！请先输入文本，并保存。"));
        msg.addButton(tr("好的"), QMessageBox::AcceptRole);
        msg.setWindowFlags(Qt::WindowStaysOnTopHint);
        msg.exec();
        return;
    }

    QFileDialog dlg(0, Qt::WindowStaysOnTopHint);
    dlg.setWindowTitle(tr("另存文件"));
    QSettings camSetting("SGX", "SGX-TEXT");
    QString path = camSetting.value(SavePath, QDir::homePath()).toString();
    dlg.setAcceptMode(QFileDialog::AcceptSave);
    dlg.setFileMode(QFileDialog::AnyFile);
    dlg.setOption(QFileDialog::DontUseNativeDialog, false);
    dlg.setDirectory(path);
    dlg.setNameFilters(QStringList() << tr("SGX文件(*.sgx *.SGX)")
                       << tr("ISO文件(*.iso *.ISO)"));
    if (!dlg.exec())
        return;
    if (dlg.selectedFiles().size() < 1) // User canceled
        return;
    QString filename = dlg.selectedFiles().at(0);
    if (filename.isEmpty())
        return;
    camSetting.setValue(SavePath, QDir(filename).absolutePath());
    if (!filename.endsWith(".sgx", Qt::CaseInsensitive) &&
            !filename.endsWith(".iso", Qt::CaseInsensitive))
    {
        QString suffixInfo = dlg.selectedNameFilter();
        if (suffixInfo.contains("sgx"))
            filename.append(".sgx");
        else if (suffixInfo.contains("iso"))
        filename.append(".iso");
    }
    QFile saveFile(filename);
    saveFile.open(QFile::WriteOnly);
    textFile2.open(QFile::ReadOnly);
    /*int wLen =*/ saveFile.write(textFile2.readAll());
//    if (wLen >= 20)
//    {
        QMessageBox msg(QMessageBox::Information, tr("保存成功"),
                        tr("已保存加工任务文件！"));
        msg.addButton(tr("好的"), QMessageBox::AcceptRole);
        msg.setWindowFlags(Qt::WindowStaysOnTopHint);
        msg.exec();
//        reject();
//    }
//    else
//    {
//        QMessageBox msg(QMessageBox::Warning, tr("保存失败"),
//                        tr("保存加工任务文件失败！请重试！"));
//        msg.addButton(tr("好的"), QMessageBox::AcceptRole);
//        msg.setWindowFlags(Qt::WindowStaysOnTopHint);
//        msg.exec();
//    }
}

void TextEdit::on_pushButton_5_clicked()
{
    QString filePath;
    filePath = QFileDialog::getOpenFileName(0, QObject::tr("打开文本文件"),
                                              QDir::homePath() + "/Desktop",
                                              QObject::tr("SGX文件(*.sgx *.SGX)"));
    if (filePath == "") return;
    QFile file(filePath);
    file.open(QFile::ReadOnly | QFile::Text);
    QString content;
    while (!file.atEnd()) content = file.readAll();
    ui->textEdit->setText(content);
}
